#!/usr/bin/python2.6
# -*- coding: utf-8 -*-

import BaseHTTPServer
import SimpleHTTPServer
import CGIHTTPServer
import cgi
import lxml

import cgitb
cgitb.enable()



HTML_TEMPLATE = """
<html
<head>
    %s
</head>
<body>
    <form action='/' method='post'>
        <input type='text' name='a' value='%s'>
        <input type='submit' value='push me!!!'>
    </form>
    %s
</body>
</html>
"""

class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def doHandleRequest(self, method):
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()

        p = (self.path.split('?', 1) + [''])[1]
        form = cgi.FieldStorage(fp = self.rfile, 
                                environ = {
                                            'QUERY_STRING':     p, 
                                            'REQUEST_METHOD':   method, 
                                            'CONTENT_TYPE':     self.headers.get('Content-Type', ''),
                                            'CONTENT_LENGTH':   self.headers.get('Content-Length', '')
                                          }
                                )

        content = '<hr>'
        a = form['a'].value if 'a' in form else ''
        content += a

        self.wfile.write(HTML_TEMPLATE % ('', a, content))
        self.wfile.close()

    def do_GET(self):
        self.doHandleRequest('GET')
    def do_POST(self):
        self.doHandleRequest('POST')


def run(server_class = BaseHTTPServer.HTTPServer, handler_class = BaseHTTPServer.BaseHTTPRequestHandler):
    try:
        server_address = ('', 8080)
        server = server_class(server_address, handler_class)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()
        print ''
        print 'Server terminated by keyboard interrupt.'

def main():
    run(handler_class = RequestHandler)

if __name__ == '__main__':
    main()
